﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using com.paypal.sdk.util;
using BLL;
using Models;
using System.Xml;
using com.paypal.sdk.services;
using System.Data;
using Web.Old_App_Code;

public partial class paypal_DoExpressCheckoutByPaypal : System.Web.UI.Page
{
    // Fields
    protected ExpenseRecords er = new ExpenseRecords();
    protected ExpenseRecordsManager erm = new ExpenseRecordsManager();
    protected GroupBuyOrderManager gbom = new GroupBuyOrderManager();
    protected GoodsPromotionManager gpm = new GoodsPromotionManager();
    protected OrderManager om = new OrderManager();
    protected string remindSetXmlPath = "/xml/remind_set.xml";
    protected UserManager um = new UserManager();
    protected User user = new User();

    // Methods
    private void ECReceiptLink_ServerClick(object sender, EventArgs e)
    {
        NVPCallerServices services = PayPalAPI.PayPalAPIInitialize();
        NVPCodec codec = new NVPCodec();
        codec["METHOD"] = "DoExpressCheckoutPayment";
        codec["TOKEN"] = this.Session["TOKEN"].ToString();
        codec["PAYERID"] = this.Session["PAYERID"].ToString();
        codec["AMT"] = this.Session["Amount"].ToString();
        codec["PAYMENTACTION"] = base.Request.QueryString["paymentType"];
        codec["CURRENCYCODE"] = base.Request.QueryString["currency"];
        string requestnvp = codec.Encode();
        string nvpstring = services.Call(requestnvp);
        NVPCodec decoder = new NVPCodec();
        decoder.Decode(nvpstring);
        string str3 = decoder["ACK"];
        if ((str3 != null) && ((str3 == "Success") || (str3 == "SuccessWithWarning")))
        {
            DataRow row;
            XmlDocument document;
            XmlElement element;
            XmlElement element2;
            string str7;
            SendMailMessage message;
            DataTable allEnabledMail;
            Random random;
            DataRow row3;
            string transactionPara = GetTransactionPara(decoder, "TRANSACTIONID");
            string orderNo = base.Request.QueryString["OrderID"];
            string str6 = GetTransactionPara(decoder, "AMT");
            DataTable userById = this.um.GetUserById((this.Session["user"] as User).Id);
            if (base.Request.QueryString["pt"] == "1")
            {
                this.om.ModifyPayStatusByOrderNo(orderNo, 1);
                if (this.Session["user"] != null)
                {
                    row = this.om.GetOrderByOrderNo(orderNo).Rows[0];
                    DataRow row2 = userById.Rows[0];
                    this.user.Id = Convert.ToInt32(row2["id"]);
                    this.user.Money = Convert.ToDecimal(row2["money"]);
                    this.user.PayPoints = Convert.ToInt32(row2["payPoints"]) + Convert.ToInt32(row["presentedIntegra"]);
                    if (this.um.ModifyUserMoneyAndPayPoints(this.user) && this.om.ModifyPayStatusByOrderNo(orderNo, 1))
                    {
                        this.om.ModifyPaymentByOrderNo(orderNo, "Paypal", "Paypal");
                        document = new XmlDocument();
                        document.Load(HttpContext.Current.Server.MapPath(this.remindSetXmlPath));
                        element = document.SelectSingleNode("set") as XmlElement;
                        element2 = document.SelectSingleNode("set").ChildNodes[1] as XmlElement;
                        str7 = File.ReadAllText(base.Server.MapPath("/cn/txt_template/order_payment.txt"));
                        if (element2.GetAttribute("mail_remind") == "true")
                        {
                            message = new SendMailMessage();
                            message.subject = "订单支付成功";
                            message.body = str7.Replace("[userName]", (this.Session["user"] as User).UserName).Replace("[orderNo]", row["orderNo"].ToString()).Replace("[orderTotal]", string.Format("{0:C}", Convert.ToDecimal(row["orderTotal"])));
                            message.html = true;
                            allEnabledMail = new MailManager().GetAllEnabledMail();
                            random = new Random();
                            row3 = allEnabledMail.Rows[random.Next(allEnabledMail.Rows.Count - 1)];
                            message.from = row3["fromAddress"].ToString();
                            message.fromName = row3["fromName"].ToString();
                            message.mailDomain = row3["mailDomain"].ToString();
                            message.mailDomainPort = Convert.ToInt32(row3["mailDomainPort"]);
                            message.mailServerUserName = row3["mailServerUserName"].ToString();
                            message.mailServerPassWord = row3["mailServerPassWord"].ToString();
                            if (element2.GetAttribute("notice_member") == "true")
                            {
                                message.mailTo = (this.Session["user"] as User).Email;
                                message.RuleSend();
                            }
                            if (element2.GetAttribute("notice_admin") == "true")
                            {
                                message.mailTo = element.GetAttribute("remind_email");
                                message.RuleSend();
                            }
                        }
                    }
                }
                base.Response.Redirect("/member_center/order_info.html?orderNo=" + orderNo);
            }
            else if (base.Request.QueryString["pt"] == "2")
            {
                this.gbom.ModifyPayStatusByOrderNo(orderNo, 1);
                if (this.Session["user"] != null)
                {
                    row = this.gbom.GetGroupBuyOrderByOrderNo(orderNo).Rows[0];
                    if (this.gbom.ModifyOrderStatusByOrderNo(orderNo, 1))
                    {
                        this.gbom.ModifyPaymentByOrderNo(orderNo, "Paypal", "Paypal");
                        document = new XmlDocument();
                        document.Load(HttpContext.Current.Server.MapPath(this.remindSetXmlPath));
                        element = document.SelectSingleNode("set") as XmlElement;
                        element2 = document.SelectSingleNode("set").ChildNodes[1] as XmlElement;
                        str7 = File.ReadAllText(base.Server.MapPath("/cn/txt_template/order_payment.txt"));
                        if (element2.GetAttribute("mail_remind") == "true")
                        {
                            message = new SendMailMessage();
                            message.subject = "订单支付成功";
                            message.body = str7.Replace("[userName]", (this.Session["user"] as User).UserName).Replace("[orderNo]", row["orderNo"].ToString()).Replace("[orderTotal]", string.Format("{0:C}", Convert.ToDecimal(row["orderTotal"])));
                            message.html = true;
                            allEnabledMail = new MailManager().GetAllEnabledMail();
                            random = new Random();
                            row3 = allEnabledMail.Rows[random.Next(allEnabledMail.Rows.Count - 1)];
                            message.from = row3["fromAddress"].ToString();
                            message.fromName = row3["fromName"].ToString();
                            message.mailDomain = row3["mailDomain"].ToString();
                            message.mailDomainPort = Convert.ToInt32(row3["mailDomainPort"]);
                            message.mailServerUserName = row3["mailServerUserName"].ToString();
                            message.mailServerPassWord = row3["mailServerPassWord"].ToString();
                            if (element2.GetAttribute("notice_member") == "true")
                            {
                                message.mailTo = (this.Session["user"] as User).Email;
                                message.RuleSend();
                            }
                            if (element2.GetAttribute("notice_admin") == "true")
                            {
                                message.mailTo = element.GetAttribute("remind_email");
                                message.RuleSend();
                            }
                        }
                    }
                }
                base.Response.Redirect("/member_center/group_buy_order_info.html?orderNo=" + orderNo);
            }
            else if (base.Request.QueryString["pt"] == "0")
            {
                if (this.Session["user"] != null)
                {
                    this.er.OrderNo = orderNo;
                    this.er.ExpenseUser = (this.Session["user"] as User).Id;
                    this.er.ExpenseMoney = Convert.ToDecimal(base.Request.QueryString["amount"]);
                    this.er.ExpenseRemark = "预存金额";
                    this.er.ExpenseType = 0;
                    if (this.erm.AddExpenseRecords(this.er))
                    {
                        DataTable table4 = this.gpm.GetPresentedIntegral(6, this.er.ExpenseMoney, "zh-CN");
                        if (table4.Rows.Count > 0)
                        {
                            this.user.Id = this.er.ExpenseUser;
                            this.user.Money = Convert.ToDecimal(userById.Rows[0]["money"]) + this.er.ExpenseMoney;
                            this.user.PayPoints = Convert.ToInt32(userById.Rows[0]["payPoints"]) + Convert.ToInt32(table4.Rows[0]["presentedIntegral"]);
                            this.um.ModifyUserMoneyAndPayPoints(this.user);
                        }
                        document = new XmlDocument();
                        document.Load(HttpContext.Current.Server.MapPath(this.remindSetXmlPath));
                        element = document.SelectSingleNode("set") as XmlElement;
                        element2 = document.SelectSingleNode("set").ChildNodes[1] as XmlElement;
                        str7 = File.ReadAllText(base.Server.MapPath("/cn/txt_template/online_payment.txt"));
                        if (element2.GetAttribute("mail_remind") == "true")
                        {
                            message = new SendMailMessage();
                            message.subject = "订单支付成功";
                            message.body = str7.Replace("[userName]", (this.Session["user"] as User).UserName).Replace("[orderNo]", this.er.OrderNo).Replace("[orderTotal]", string.Format("{0:C}", Convert.ToDecimal(this.er.ExpenseMoney)));
                            message.html = true;
                            allEnabledMail = new MailManager().GetAllEnabledMail();
                            random = new Random();
                            row3 = allEnabledMail.Rows[random.Next(allEnabledMail.Rows.Count - 1)];
                            message.from = row3["fromAddress"].ToString();
                            message.fromName = row3["fromName"].ToString();
                            message.mailDomain = row3["mailDomain"].ToString();
                            message.mailDomainPort = Convert.ToInt32(row3["mailDomainPort"]);
                            message.mailServerUserName = row3["mailServerUserName"].ToString();
                            message.mailServerPassWord = row3["mailServerPassWord"].ToString();
                            if (element2.GetAttribute("notice_member") == "true")
                            {
                                message.mailTo = (this.Session["user"] as User).Email;
                                message.RuleSend();
                            }
                            if (element2.GetAttribute("notice_admin") == "true")
                            {
                                message.mailTo = element.GetAttribute("remind_email");
                                message.RuleSend();
                            }
                        }
                    }
                }
                base.Response.Redirect("/cn/member_center/expense_records.html");
            }
        }
        else
        {
            this.Session["errorresult"] = decoder;
            string str8 = "API=Error Detail ";
            base.Response.Redirect("APIError.aspx?" + str8);
        }
    }

    public static string GetTransactionPara(NVPCodec decoder, string keyName)
    {
        if (decoder != null)
        {
            return decoder[keyName];
        }
        return "Error,not found";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string str2;
        NVPCallerServices services = PayPalAPI.PayPalAPIInitialize();
        NVPCodec codec = new NVPCodec();
        codec["METHOD"] = "GetExpressCheckoutDetails";
        codec["TOKEN"] = this.Session["TOKEN"].ToString();
        string requestnvp = codec.Encode();
        int num = 10;
        int num2 = 0;
    Label_004D: ;
        try
        {
            str2 = services.Call(requestnvp);
        }
        catch (Exception exception)
        {
            if (num2 < num)
            {
                num2++;
                goto Label_004D;
            }
            base.Response.Write(exception.Message);
            base.Response.Flush();
            base.Response.End();
            return;
        }
        NVPCodec response = new NVPCodec();
        response.Decode(str2);
        string str3 = response["ACK"];
        if ((str3 != null) && ((str3 == "Success") || (str3 == "SuccessWithWarning")))
        {
            string str4 = Util.BuildResponse(response, "Review Order", "Step 3: DoExpressCheckoutPayment");
            this.Session["PAYERID"] = response["PAYERID"];
            this.Session["Amount"] = response["AMT"];
            this.ECReceiptLink_ServerClick(null, null);
        }
        else
        {
            this.Session["errorresult"] = response;
            string str5 = "API=Error Detail ";
            base.Response.Redirect("APIError.aspx?" + str5);
        }
    }

    // Properties
    private int OrderID
    {
        get
        {
            int num;
            if (!int.TryParse(base.Request["OrderID"], out num))
            {
                num = -1;
            }
            return num;
        }
    }

}